const express = require(`express`);
const { recursionDataTree} = require('../../utils/index')
const db_query = require('../../utils/db_query');
const db = require('../../utils/db_connect');
const router = express.Router();
const fs = require('fs');
const xss = require('xss');
const COS = require('cos-nodejs-sdk-v5');
const http = require('http')

let myxss = new xss.FilterXSS({
    whiteList: {
        a: ["href", "title", "target"],
    },
});
// 以后直接调用 myxss.process() 来处理即可
// html = myxss.process('<script>alert("xss");</script>');

var cos = new COS({
    AppId: '1253860470',
    SecretId: 'AKIDWv9MTOhcw4xrdFvy77wYyBD5lEVefGoC',
    SecretKey: 'KUWO3WmqhMo494nOn05yfDbnnaBanpne',
});


//获取规范管理员
async function getAdmin(id,user_id,res){

    let queryAdmin = `SELECT admin_list FROM standard WHERE id=${id}`;
    let data = await db(queryAdmin);
    console.log(data[0].admin_list.indexOf(','+user_id+',') == -1);
    if(data[0].admin_list.indexOf(','+user_id+',') == -1){
        return false
    }else{
        return true
    }
}
//获取详情规范id
async function getStandId(id,user_id,res){
    let stand_id_sql = `SELECT standard_id FROM standard_detail WHERE id=${id}`;
    // let queryArr = [id];
    let data = await db(stand_id_sql);
    return getAdmin(data[0].standard_id,user_id,res)
    // db_query(stand_id_sql,queryArr,res,(err,data)=>{
    //     return getAdmin(data[0].standard_id,queryArr,user_id,res)
    // })
    
}



//规范列表
router.get('/standard/list',(req,res)=>{

    let params = req.query;
    let sql = '';
    let sqlArr = [];
    params.keyword = myxss.process(params.keyword);
    if (params.type) {

        //获取体验规范或都品牌规范
        if (params.category_id !== '') {

            //按规范分类查找
            sql = `SELECT * FROM standard where type=? AND category_id=? AND status=1 AND (auth_status=1 OR (auth_status=0 AND (admin_list Like "%${params.user_id}%" OR member_list Like "%${params.user_id}%"))) ORDER BY sort ASC `
            sqlArr = [params.type,params.category_id]
        } else {

            if (params.keyword && params.keyword != '') {

                //关键字查找
                sql = `SELECT * FROM standard where type=? AND name Like "%${params.keyword}%"  AND status=1  AND (auth_status=1 OR (auth_status=0 AND (admin_list Like "%${params.user_id}%" OR member_list Like "%${params.user_id}%"))) ORDER BY sort ASC `
                sqlArr = [params.type]
            } else {

                //品牌或体验规范
                sql = `SELECT * FROM standard where type=? AND status=1 AND (auth_status=1 OR (auth_status=0 AND (admin_list Like "%${params.user_id}%" OR member_list Like "%${params.user_id}%"))) ORDER BY sort ASC `
                sqlArr = [params.type]
            }
        }
    } else {

        //查找我的规范根据user_id
        sql = `SELECT stand.* FROM standard stand left join member m on stand.user_id=m.id where stand.user_id=? order by status desc`;
        sqlArr = [params.user_id]
    }

    db_query(sql,sqlArr,res,(err,data)=>{

        if(err) return

        res.send({
            code:'200',
            message:'查询成功',
            data:data
        })
    })
    
})

//后台规范列表
router.get('/standard/admin_list',(req,res)=>{

    let roleArr = ['1','2']
    if(!roleArr.includes(req.headers.role)){
        res.send({
            code: '401',
            message: '你没有权限访问',
            data: null
        })
        return;
    }

    let params = req.query;
    params.keyword = myxss.process(params.keyword);
    let sql = `SELECT * FROM standard where type=? AND status=1 AND name Like  "%${params.keyword}%" ORDER BY sort ASC`;
    let sqlArr = [params.type];
    if(params.category_id){
        sql = `SELECT * FROM standard where type=? AND status=1 AND category_id=? ORDER BY sort ASC `;
        sqlArr = [params.type,params.category_id]
    }

    db_query(sql,sqlArr,res,(err,data)=>{

        if(err) return

        res.send({
            code:'200',
            message:'查询成功',
            data:data
        })
    })
})

//创建规范
router.post('/standard/add',(req,res)=>{

    let {name,domain,type,category_id,dept_id,status,covar_path,auth_status,admin_list,member_list,auth_dept,user_id} = req.body;
    name=myxss.process(name);
    domain=myxss.process(domain);
    let sql = `INSERT INTO standard(name,domain,type,category_id,dept_id,status,covar_path,auth_status,admin_list,member_list,auth_dept,user_id,create_time) values(?,?,?,?,?,?,?,?,?,?,?,?,now())`;
    let sqlArr = [name,domain,type,category_id,dept_id,status,covar_path,auth_status,admin_list,member_list,auth_dept,user_id]

    db_query(sql,sqlArr,res,(err,data)=>{
        if(err) return
        db_query('select id from standard ORDER BY id desc limit 1',[],res,(error,id)=>{
            if(error) return
            
            res.send({
                code:'200',
                message:'查询成功',
                data:null,
                id:id[0].id
            })
        })

    })

})

//获取规范详情
router.get('/standard/data',(req,res)=>{
    let id = req.query.id;
    let sql = `SELECT * FROM standard WHERE id=?`;
    let sqlArr = [id]
    db_query(sql,sqlArr,res,(err,data)=>{
        if(err) return
        res.send({
            code:'200',
            message:'删除成功',
            data:data[0]
        })
    })
})


//删除规范
router.post('/standard/delete',async (req,res)=>{

    let {id} = req.body;
    let roleArr = ['1','2'];

    if(!roleArr.includes(req.headers.role) || !getAdmin(id,req.headers.user,res)){
        res.send({
            code: '401',
            message: '你没有删除权限',
            data: null
        })
        return;
    }
    let sql = 'DELETE FROM standard WHERE id=? ';
    let sqlArr = [id];
    db_query(sql,sqlArr,res,(err,data)=>{

        if(err) return

        res.send({
            code:'200',
            message:'删除成功',
            data:null
        })
    })


})


//更改规范状态
router.post('/standard/update_status',(req,res)=>{
    let {status,standard_id} = req.body;
    if(!getAdmin(standard_id,req.headers.user,res)){
        res.send({
            code: '401',
            message: '你没有权限操作',
            data: null
        })
        return;
    }

    let sql = `UPDATE standard SET status=?  WHERE id=?`;
    let sqlArr = [status,standard_id]
    db_query(sql,sqlArr,res,(err,data)=>{

        if(err) return

        res.send({
            code:'200',
            message:'更新成功',
            data:null
        })
    })
})

//更改规范封面
router.post('/standard/update_covar',(req,res)=>{
    let {covar_path,id} = req.body;
    if(!getAdmin(id,req.headers.user,res)){
        res.send({
            code: '401',
            message: '你没有权限操作',
            data: null
        })
        return;
    }
    let sql = `UPDATE standard SET covar_path=?  WHERE id=?`;
    let sqlArr = [covar_path,id]
    db_query(sql,sqlArr,res,(err,data)=>{

        if(err) return

        res.send({
            code:'200',
            message:'更新成功',
            data:null
        })
    })
})

//更改规范名称
router.post('/standard/update_name',(req,res)=>{
    let {name,id} = req.body;
    name=myxss.process(name);
    if(!getAdmin(id,req.headers.user,res)){
        res.send({
            code: '401',
            message: '你没有权限操作',
            data: null
        })
        return;
    }
    let sql = `UPDATE standard SET name=?  WHERE id=?`;
    let sqlArr = [name,id]
    db_query(sql,sqlArr,res,(err,data)=>{

        if(err) return

        res.send({
            code:'200',
            message:'更新成功',
            data:null
        })
    })
})


//规范排序
router.post('/standard/sort',(req,res)=>{
    let roleArr = ['1','2']
    if(!roleArr.includes(req.headers.role)){
        res.send({
            code: '401',
            message: '你没有权限访问',
            data: null
        })
        return;
    }
    let {type,category_id,keyword,ids} = req.body;
    keyword=myxss.process(keyword);
    let itemsSql = `SELECT sort FROM standard WHERE type=? AND status=1 ORDER BY sort ASC`;
    let itemArr = [type]
    if(category_id){
        itemsSql = `SELECT sort FROM standard WHERE type=? AND category_id=? AND status=1 ORDER BY sort ASC`;
        itemArr = [type,category_id]
    }
    if(keyword){
        itemsSql = `SELECT sort FROM standard WHERE type=? AND name LIKE "%?%" AND status=1 ORDER BY sort ASC`;
        itemArr = [type,keyword]
    }
    db_query(itemsSql,itemArr,res,(err,data)=>{

        if(err) return

        let items = data;
        items.forEach(async(element,index) => {
            let s = `SELECT id,sort FROM standard WHERE id =${ids[index]}`;
            let res = await db(s);
            if(element.sort != res[0].sort){
                let sql_ = `UPDATE standard SET sort=${element.sort}  WHERE id=${res[0].id}`
                let d =await db(sql_);
            }
        });

        res.send({
            code:'200',
            message:'保存成功',
            data:null
        })

    })
})


//规范分类
router.get('/standard/category', (req, res) => {
    let sql = 'SELECT * FROM standard_category';
    db_query(sql,[],res,(err,data)=>{

        if(err) return

        res.send({
            code:'200',
            message:'请求成功',
            data:data
        })
    })
})

//获取规范详情内容
router.get('/standard/details',(req,res)=>{
    let {standard_id} = req.query
    let sql = `SELECT * FROM standard_detail WHERE standard_id=? ORDER BY sort ASC`;
    let sqlArr = [standard_id]
    db_query(sql,sqlArr,res,(err,data)=>{
        if(err) return
        let menuData = recursionDataTree(data, 0);
        res.send({
            code:'200',
            message:'请求成功',
            data:menuData
        })
    })
})


//新增规范树节点
router.post('/standard/details/addNode',(req,res)=>{

    let {standard_id,name,parent_id,description,user_id,user_name,type} = req.body;
    name=myxss.process(name);
    description=myxss.process(description);
    user_name=myxss.process(user_name);
    if(!getAdmin(standard_id,req.headers.user,res)){
        res.send({
            code: '401',
            message: '你没有权限操作',
            data: null
        })
        return;
    }
    if(!parent_id) parent_id = 0;

    let sql = `INSERT INTO standard_detail(standard_id,name,parent_id,description,user_id,user_name,type,create_time) values(?,?,?,?,?,?,?,now())`;
    let sqlArr = [standard_id,name,parent_id,description,user_id,user_name,type]
    db_query(sql,sqlArr,res,(err,data)=>{

        if(err) return;
        let sqlSub = `UPDATE standard_detail SET sort=? WHERE id=?`;
        let sqlSubArr = [data.insertId,data.insertId]
        db_query(sqlSub,sqlSubArr,res,(err,r)=>{
            console.log(err)
        })
        res.send({
            code:'200',
            message:'创建成功',
            data:null
        })
    })
})

//节点重命名
router.post('/standard/details/updateNode',(req,res)=>{
    let {name,id} = req.body;
    if(!getStandId(id,req.headers.user,res)){
        res.send({
            code: '401',
            message: '你没有权限操作',
            data: null
        })
        return;
    }
    
    let sql = `UPDATE standard_detail SET name=? WHERE id=?`;
    let sqlArr = [name,id]
    name=myxss.process(name);
    db_query(sql,sqlArr,res,(err,data)=>{

        if(err) return

        res.send({
            code:'200',
            message:'更新成功',
            data:null
        })
    })
})

//节点删除
router.post('/standard/details/deleteNode',(req,res)=>{

    if(!getStandId(req.body.id,req.headers.user,res)){
        res.send({
            code: '401',
            message: '你没有权限操作',
            data: null
        })
        return;
    }

    let sql = `DELETE FROM standard_detail WHERE id=?`;
    let sqlArr = [req.body.id];
    db_query(sql,sqlArr,res,(err,data)=>{

        if(err) return

        res.send({
            code:'200',
            message:'删除成功',
            data:null
        })
    })
})

//规范详情节点排序
router.post('/standard/details/sort',(req,res)=>{
    let {standard_id,ids} = req.body;

    if(!getAdmin(standard_id,req.headers.user,res)){
        res.send({
            code: '401',
            message: '你没有权限操作',
            data: null
        })
        return;
    }


    let itemsSql = `SELECT sort FROM standard_detail WHERE standard_id=? AND parent_id=0 ORDER BY sort ASC`
    let sqlArr = [standard_id]
    // if(category_id){
    //     itemsSql = `SELECT sort FROM standard WHERE type=${type} AND category_id=${category_id} AND status=1 ORDER BY sort ASC`
    // }
    // if(keyword){
    //     itemsSql = `SELECT sort FROM standard WHERE type=${type} AND name LIKE "%${keyword}%" AND status=1 ORDER BY sort ASC`
    // }
    db_query(itemsSql,sqlArr,res,(err,data)=>{

        if(err) return

        let items = data;
        items.forEach(async(element,index) => {
            let s = `SELECT id,sort FROM standard_detail WHERE id =${ids[index]}`
            let res = await db(s);
            if(element.sort != res[0].sort){
                let sql_ = `UPDATE standard_detail SET sort=${element.sort}  WHERE id=${res[0].id}`
                let d =await db(sql_);
            }
        });

        res.send({
            code:'200',
            message:'保存成功',
            data:null
        })

    })
})

//保存详情内容
router.post('/standard/details/updateDetail',(req,res)=>{
    let {description,user_name,user_id,id} = req.body;
    // description=myxss.process(description);

    if(!getStandId(id,req.headers.user,res)){
        res.send({
            code: '401',
            message: '你没有权限操作',
            data: null
        })
        return;
    }
    let sql = `UPDATE standard_detail SET description=?,user_name=?,user_id=? WHERE id=?`;
    


    fs.writeFile('index.html',description,(err)=>{
        if(err) throw err;
        console.log('创建文件成功');
        cos.sliceUploadFile({
            Bucket:'test-1253860470',
            Region: 'ap-nanjing',
            Key:'d'+user_id+''+id+'.html',
            FilePath:'./index.html'
        },function(err,data){
            if(!err){
                description = 'http://'+ data['Location'];
                let sqlArr = [description,user_name,user_id,id];
                db_query(sql,sqlArr,res,(error,data)=>{
                    if(error) return
                    res.send({
                        code:'200',
                        message:'修改成功',
                        data:null
                    })
                })
            }else{
                console.log(err,'<==>');
            }
        })
    })
    return;
    
})

//获取详情文件文本内容
router.get('/standard/details/descText',(req,res)=>{
    console.log(111);
    let {id} = req.query;
    let sql = 'SELECT description from standard_detail WHERE id=?'
    let sqlArr = [id];
    db_query(sql,sqlArr,res,(error,data)=>{
        if(error) return;
        console.log(data);
        http.get(data[0].description).on('response', function (response) {
            response.on('data', function (chunk) { 
                let txt = Buffer(chunk);
                res.send({
                    code:'200',
                    message:'修改成功',
                    data:txt.toString()
                })
            }); 
        })
        return;
        // console.log(result.toString());
        res.send({
            code:'200',
            message:'修改成功',
            data:result
        })
    })
})

module.exports = router